// 定义类型别名来描述用户信息的结构
/**
 *
 *
 * @property {string} username - 用户名
 * @property {string} password - 密码
 */
import { ElMessage } from 'element-plus'
import store from './../store'
import IndexedDBManager from './../db/db'

async function ObtainJWT() {
  const dbName = 'dexcpro';
  const storeName = 'user';
  let dexcuser = new IndexedDBManager(dbName, storeName);
  let JWT = await dexcuser.getObject(1)
  if (JWT) {
    return JWT.JWT
  } else {
    return '';
  }
}

async function dataRequest(data, Version = 'v1', Controller = 'api') {
  try {
    let JWT = await ObtainJWT()
    //! https://v1.dexc.pro/项目名称/版本/控制器/方法
    //! https://v1.dexc.pro/edu/v1/api/too
    const response = await fetch(`https://v1.dexc.pro/edu/${Version}/${Controller}/${data[0]}`, {
      method: 'POST',
      mode: 'cors', // 设置为 cors 模式
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Content-Length': JSON.stringify(data[1]).length.toString(),
        'Authorization': JWT, // 添加包含JWT令牌的Authorization头部
      },
      body: JSON.stringify(data[1]),
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const returndata = await response.json();
    return returndata;
  } catch (error) {
    console.log(error)
    if (error.response && error.response.status === 503) {
      console.log('503错误 - 服务器暂时不可用');
      // 在这里可以执行相应的操作，比如显示一个提示，或进行重试等
    }
    return false;
  }
}

async function filesRequest(data) {
  try {
    let JWT = await ObtainJWT()
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), 30000);
    // https://api.dexc.pro/api.php?` + data[0]
    let response = await fetch(`https://v1.dexc.pro/edu/v1/api/${data[0]}`, {
      method: 'POST',
      signal: controller.signal,
      headers: {
        'Authorization': JWT, // 添加包含JWT令牌的Authorization头部
      },
      body: data[1],
    });
    const games = await response.json();
    clearTimeout(id);
    return games;
  } catch (error) {
    return { code: 408, data: error, massage: '超时', state: 'error' };
  }
}

async function fileUploadRequest(ele, quill) {
  var formData = new FormData();
  formData.append('file', ele.file);
  let a = await filesRequest(['files', formData]);
  const { index, length } = quill.selection.savedRange;
  const selectedText = quill.getText(index, length);
  const newText = selectedText.toUpperCase();
  quill.deleteText(index, length);
  quill.insertText(index, newText);
  quill.setSelection(index, newText.length);
  if (a.code == 200) {
    quill.clipboard.dangerouslyPasteHTML(index, `<img src ="` + a.data + `" alt = "" >`);
    return true;
  } else {
    return false;
  }
}

function setText(val) {
  if (val != null && val != "") {
    var re1 = new RegExp("<.+?>|&.+?;", "g");
    var msg = val.replace(re1, "");
    msg = msg.replace(/\s/g, "");
    msg = msg.replace(/[\r\n]/g, "");
    return msg.substr(0, 100);
  } else return '';
}

// 自动登陆
async function automaticLogin() {
  let array = await dataRequest(['login', '']);
  const dbName = 'dexcpro';
  const storeName = 'user';
  let dexcuser = new IndexedDBManager(dbName, storeName);
  let JWT = await ObtainJWT()
  if (array.code == 200) {
    if (JWT) {
      const data = { id: 1, JWT: JWT, logon: true }
      dexcuser.updateObject(data)
    }
    store.commit('setLogon', true)
    store.commit('setUser', array.data)
    return array
  } else {
    store.commit('setLogon', false)
    let JWT = await dexcuser.getObject(1)
    if (array.code == 498) {
      JWT.JWT = ''
    }
    if (JWT) {
      const data = { id: 1, JWT: JWT.JWT, logon: false }
      dexcuser.updateObject(data)
    } else {
      dexcuser.addObject({ id: 1, JWT: '', logon: false })
    }
    return array
  }
}
// // 检查登陆状态
// async function Loginjudgment() {
//   const dbName = 'dexcpro';
//   const storeName = 'user';
//   let dexcuser = new IndexedDBManager(dbName, storeName);
//   // 这里可能有问题
//   let arr = await dexcuser.getObject(1)
//   console.log(arr)
//   if (!arr.logon) {
//     ElMessage.error('请先登陆')
//     router.push({ path: '/' })
//   }
// }
// 退出登陆
async function Logoutoflogin() {
  const dbName = 'dexcpro';
  const storeName = 'user';
  let dexcuser = new IndexedDBManager(dbName, storeName);
  const data = { id: 1, JWT: '', logon: false }
  if (await dexcuser.getObject(data.id)) {
    // 存在修改
    dexcuser.updateObject(data)

  } else {
    // 不存在 添加
    dexcuser.addObject(data)

  }
  store.commit('setLogon', false)
  store.commit('setUser', null)

  setTimeout(() => {
    location.reload(true)
    ElMessage.success('退出成功')
  }, 1000);


}



export { dataRequest, filesRequest, fileUploadRequest, setText, automaticLogin, Logoutoflogin };